import React from "react";
import { createSchemaField, ISchema } from "@formily/react";
import { useNavigate } from "react-router-dom";
import { FormDialog, FormLayout, FormItem, Select } from "@formily/antd";
import { Button } from "antd";
import { ImportOutlined } from "@ant-design/icons";
import FetchSelect from "src/components/FetchSelect";

interface Props {
  style?: React.CSSProperties;
}

const SelectStorageFormButton: React.FC<Props> = (props) => {
  const SchemaField = createSchemaField({
    components: {
      FormItem,
      Select,
      FetchSelect,
    },
  });

  const schema: ISchema = {
    type: "object",
    properties: {
      type: {
        type: "string",
        title: "Type",
        enum: [
          { label: "Mysql", value: "mysql" },
          { label: "Redis", value: "redis" },
          { label: "MongoDB", value: "mongodb" },
        ],
        "x-decorator": "FormItem",
        "x-component": "Select",
      },
      storageUri: {
        type: "string",
        title: "StorageUri",
        "x-decorator": "FormItem",
        "x-component": "FetchSelect",
      },
    },
  };

  const navigate = useNavigate();
  const handleClick = () => {
    FormDialog("选择要绑定的 Storage", () => {
      return (
        <FormLayout labelCol={6} wrapperCol={16}>
          <SchemaField schema={schema} />
        </FormLayout>
      );
    })
      .forConfirm((form, next) => {
        console.log(form.values);

        navigate(
          `/entity/form?operate=add&storageUri=${form.values.storageUri}`
        );
        next(form);
      })
      .forCancel((form, next) => {
        next(form);
      })
      .open()
      .then(console.log)
      .catch(console.error);
  };

  return (
    <Button
      style={props.style}
      type="primary"
      icon={<ImportOutlined />}
      onClick={handleClick}
    >
      新建
    </Button>
  );
};

export default SelectStorageFormButton;
